package com.hgyc.mom.common.util.sql;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;

/**
 * 动态获取当前数据库类型工厂类
 * @author fwj
 * @since 2025/5/3
 */
public class DialectFactory {

    public static SqlDialect getDialect(DataSource dataSource) {
        try (Connection conn = dataSource.getConnection()) {
            DatabaseMetaData metaData = conn.getMetaData();
            String dbProductName = metaData.getDatabaseProductName().toLowerCase();

            if (dbProductName.contains("mysql")) {
                return new MySqlDialect();
            } else if (dbProductName.contains("postgresql")) {
                return new PostgreSqlDialect();
            } else if (dbProductName.contains("oracle")) {
                return new OracleDialect();
            } else if (dbProductName.contains("sql server")) {
                return new SqlServerDialect();
            } else {
                throw new UnsupportedOperationException("Unsupported DB: " + dbProductName);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to detect database dialect", e);
        }
    }

}
